package bc

import (
	"github.com/flipped-aurora/gin-vue-admin/server/global"
	"github.com/flipped-aurora/gin-vue-admin/server/model/bc"
	bcReq "github.com/flipped-aurora/gin-vue-admin/server/model/bc/request"
	"github.com/flipped-aurora/gin-vue-admin/server/model/common/request"
)

type BcPhoneService struct {
}

// CreateBcPhone 创建bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) CreateBcPhone(bcPhone *bc.BcPhone) (err error) {
	err = global.GVA_DB.Create(bcPhone).Error
	return err
}

// DeleteBcPhone 删除bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) DeleteBcPhone(bcPhone bc.BcPhone) (err error) {
	err = global.GVA_DB.Delete(&bcPhone).Error
	return err
}

// DeleteBcPhoneByIds 批量删除bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) DeleteBcPhoneByIds(ids request.IdsReq) (err error) {
	err = global.GVA_DB.Delete(&[]bc.BcPhone{}, "id in ?", ids.Ids).Error
	return err
}

func (bcPhoneService *BcPhoneService) DeleteBcPhoneById(id uint) (err error) {
	err = global.GVA_DB.Delete(&[]bc.BcPhone{}, "id = ?", id).Error
	return err
}

// UpdateBcPhone 更新bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) UpdateBcPhone(bcPhone bc.BcPhone) (err error) {
	err = global.GVA_DB.Save(&bcPhone).Error
	return err
}

// GetBcPhone 根据id获取bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) GetBcPhone(id uint) (bcPhone bc.BcPhone, err error) {
	err = global.GVA_DB.Where("id = ?", id).First(&bcPhone).Error
	return
}

func (bcPhoneService *BcPhoneService) GetBcPhoneByProjectIDAndPhone(projectId int, phone string) (bcPhone bc.BcPhone, err error) {
	err = global.GVA_DB.Where("project_id = ? and phone = ?", projectId, phone).Find(&bcPhone).Error
	return
}

func (bcPhoneService *BcPhoneService) GetBcPhoneList(id int) (bcPhone []bc.BcPhone, err error) {
	var bcPhones []bc.BcPhone
	err = global.GVA_DB.Where("project_id = ?", id).Find(&bcPhones).Error
	return bcPhones, err
}

// GetBcPhoneInfoList 分页获取bcPhone表记录
// Author [piexlmax](https://github.com/piexlmax)
func (bcPhoneService *BcPhoneService) GetBcPhoneInfoList(info bcReq.BcPhoneSearch) (list []bc.BcPhone, total int64, err error) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&bc.BcPhone{})
	var bcPhones []bc.BcPhone
	// 如果有条件搜索 下方会自动创建搜索语句
	if info.StartCreatedAt != nil && info.EndCreatedAt != nil {
		db = db.Where("created_at BETWEEN ? AND ?", info.StartCreatedAt, info.EndCreatedAt)
	}
	err = db.Count(&total).Error
	if err != nil {
		return
	}

	if limit != 0 {
		db = db.Limit(limit).Offset(offset)
	}

	err = db.Find(&bcPhones).Error
	return bcPhones, total, err
}
